<template>
  <div class="reports-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">检查报告</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/portal/patient' }">患者服务</el-breadcrumb-item>
          <el-breadcrumb-item>检查报告</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="container main-content">
      <el-card class="search-card">
        <div class="search-header">
          <h3 class="search-title">查询条件</h3>
        </div>
        
        <el-form :inline="true" :model="searchForm" ref="searchFormRef" class="search-form">
          <el-form-item label="检查时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              :shortcuts="dateShortcuts"
              style="width: 320px"
            />
          </el-form-item>
          
          <el-form-item label="检查类型">
            <el-select v-model="searchForm.examType" placeholder="请选择检查类型" clearable style="width: 150px">
              <el-option label="全部类型" value="" />
              <el-option label="血常规" value="血常规" />
              <el-option label="生化检查" value="生化检查" />
              <el-option label="尿常规" value="尿常规" />
              <el-option label="心电图" value="心电图" />
              <el-option label="胸片" value="胸片" />
              <el-option label="CT检查" value="CT检查" />
              <el-option label="MRI检查" value="MRI检查" />
              <el-option label="B超检查" value="B超检查" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="报告状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
              <el-option label="全部状态" value="" />
              <el-option label="已出报告" value="completed" />
              <el-option label="检查中" value="processing" />
              <el-option label="待检查" value="pending" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon> 查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><RefreshLeft /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <el-card class="reports-card">
        <div class="reports-header">
          <h3 class="reports-title">检查报告列表</h3>
          <div class="reports-stats">
            <span class="stat-item">共 {{ pagination.total }} 条报告</span>
            <span class="stat-item">待查看 {{ unreadCount }} 条</span>
          </div>
        </div>
        
        <el-table 
          :data="reportsList" 
          v-loading="loading"
          style="width: 100%"
          stripe
          @row-click="handleRowClick"
        >
          <el-table-column prop="examDate" label="检查日期" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.examDate) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="examType" label="检查类型" width="120" />
          
          <el-table-column prop="examName" label="检查项目" show-overflow-tooltip />
          
          <el-table-column prop="department" label="检查科室" width="120" />
          
          <el-table-column prop="doctorName" label="申请医生" width="120" />
          
          <el-table-column prop="status" label="报告状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="isRead" label="查看状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.isRead ? 'success' : 'warning'" size="small">
                {{ scope.row.isRead ? '已查看' : '未查看' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="300" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click.stop="handleViewReport(scope.row)"
                  :disabled="scope.row.status !== 'completed'"
                >
                  查看报告
                </el-button>
                <el-button 
                  size="small" 
                  type="success" 
                  @click.stop="handleDownloadReport(scope.row)"
                  :disabled="scope.row.status !== 'completed'"
                >
                  下载报告
                </el-button>
                <el-button 
                  size="small" 
                  type="info" 
                  @click.stop="handleViewHistory(scope.row)"
                >
                  检查历史
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="pagination"
        />
      </el-card>
    </div>
    
    <!-- 报告详情弹窗 -->
    <el-dialog
      v-model="reportDialogVisible"
      title="检查报告详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <div v-if="currentReport" class="report-detail">
        <div class="report-header">
          <h3>{{ currentReport.examName }}</h3>
          <div class="report-meta">
            <span>检查日期：{{ formatDate(currentReport.examDate) }}</span>
            <span class="divider">|</span>
            <span>报告日期：{{ formatDate(currentReport.reportDate) }}</span>
          </div>
        </div>
        
        <el-descriptions :column="2" border class="report-info">
          <el-descriptions-item label="检查类型">
            {{ currentReport.examType }}
          </el-descriptions-item>
          <el-descriptions-item label="检查科室">
            {{ currentReport.department }}
          </el-descriptions-item>
          <el-descriptions-item label="申请医生">
            {{ currentReport.doctorName }}
          </el-descriptions-item>
          <el-descriptions-item label="检查技师">
            {{ currentReport.technician || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="报告医生">
            {{ currentReport.reportDoctor || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="报告状态">
            <el-tag :type="getStatusType(currentReport.status)">
              {{ getStatusText(currentReport.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section">
          <h4>检查结果</h4>
          <div class="content-box">
            <div v-if="currentReport.results && currentReport.results.length > 0">
              <el-table :data="currentReport.results" size="small">
                <el-table-column prop="item" label="检查项目" />
                <el-table-column prop="result" label="检查结果" />
                <el-table-column prop="reference" label="参考值" />
                <el-table-column prop="unit" label="单位" />
                <el-table-column prop="status" label="状态">
                  <template #default="scope">
                    <el-tag :type="getResultStatusType(scope.row.status)" size="small">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else>
              {{ currentReport.resultText || '暂无检查结果' }}
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>报告描述</h4>
          <div class="content-box">
            {{ currentReport.description || '无' }}
          </div>
        </div>
        
        <div class="detail-section">
          <h4>诊断意见</h4>
          <div class="content-box">
            {{ currentReport.diagnosis || '无' }}
          </div>
        </div>
        
        <div class="detail-section">
          <h4>建议</h4>
          <div class="content-box">
            {{ currentReport.suggestion || '无' }}
          </div>
        </div>
        
        <div v-if="currentReport.images && currentReport.images.length > 0" class="detail-section">
          <h4>检查图像</h4>
          <div class="images-box">
            <el-image
              v-for="(image, index) in currentReport.images"
              :key="index"
              :src="image.url"
              :alt="image.name"
              style="width: 200px; height: 200px; margin: 10px;"
              fit="cover"
              :preview-src-list="currentReport.images.map(img => img.url)"
              :initial-index="index"
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="reportDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleDownloadCurrent">下载报告</el-button>
        <el-button type="success" @click="handlePrintReport">打印报告</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { patientAPI } from '@/utils/api'
import { format } from 'date-fns'
import { Search, RefreshLeft, Document, Download, View, Printer } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 数据状态
const loading = ref(false)
const reportsList = ref([])
const reportDialogVisible = ref(false)
const currentReport = ref(null)
const currentPatient = ref(null)

// 搜索表单
const searchForm = reactive({
  examType: '',
  status: ''
})

const dateRange = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 未读报告数量
const unreadCount = computed(() => {
  return reportsList.value.filter(report => !report.isRead && report.status === 'completed').length
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    'pending': 'warning',
    'processing': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    'pending': '待检查',
    'processing': '检查中',
    'completed': '已出报告',
    'cancelled': '已取消'
  }
  return texts[status] || '未知'
}

// 获取检查结果状态类型
const getResultStatusType = (status) => {
  const types = {
    '正常': 'success',
    '异常': 'danger',
    '偏高': 'warning',
    '偏低': 'warning'
  }
  return types[status] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  try {
    return format(new Date(date), 'yyyy-MM-dd')
  } catch {
    return date
  }
}

// 获取当前患者信息
const getCurrentPatient = async () => {
  try {
    const currentUserId = userStore.userInfo?.id || userStore.userInfo?._id
    console.log('当前用户ID:', currentUserId)
    
    if (!currentUserId) {
      throw new Error('未找到当前用户ID')
    }
    
    // 通过用户ID获取患者信息
    const res = await patientAPI.getPatients({ userId: currentUserId })
    console.log('患者查询响应:', res)
    
    if (res.success && res.data && res.data.patients && res.data.patients.length > 0) {
      currentPatient.value = res.data.patients[0]
      console.log('找到当前患者:', currentPatient.value)
      return currentPatient.value
    } else {
      throw new Error('未找到对应的患者信息')
    }
  } catch (error) {
    console.error('获取患者信息失败:', error)
    ElMessage.error('获取患者信息失败，请联系管理员')
    throw error
  }
}

// 加载检查报告数据
const loadReports = async () => {
  try {
    loading.value = true
    
    // 如果还没有患者信息，先获取
    if (!currentPatient.value) {
      await getCurrentPatient()
    }
    
    // 确保有患者信息
    if (!currentPatient.value) {
      ElMessage.error('未找到患者信息，无法加载检查报告')
      return
    }
    
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      patientId: currentPatient.value?.id || currentPatient.value?._id
    }
    
    console.log('查询检查报告参数:', params)
    
    // 添加搜索条件
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    if (searchForm.examType) {
      params.examType = searchForm.examType
    }
    
    if (searchForm.status) {
      params.status = searchForm.status
    }
    
    const res = await patientAPI.getReports(params)
    
    if (res.success && res.data) {
      reportsList.value = res.data.reports || res.data.items || []
      pagination.total = res.data.total || 0
    } else {
      // 如果API请求失败，使用模拟数据
      loadMockData()
    }
  } catch (error) {
    console.error('加载检查报告失败:', error)
    // 加载模拟数据
    loadMockData()
  } finally {
    loading.value = false
  }
}

// 加载模拟数据
const loadMockData = () => {
  const mockReports = [
    {
      id: '1',
      examDate: '2024-01-15',
      reportDate: '2024-01-16',
      examType: '血常规',
      examName: '血常规检查',
      department: '检验科',
      doctorName: '张医生',
      technician: '李技师',
      reportDoctor: '王医生',
      status: 'completed',
      isRead: false,
      results: [
        { item: '白细胞计数', result: '6.8', reference: '3.5-9.5', unit: '×10^9/L', status: '正常' },
        { item: '红细胞计数', result: '4.2', reference: '4.3-5.8', unit: '×10^12/L', status: '偏低' },
        { item: '血红蛋白', result: '125', reference: '130-175', unit: 'g/L', status: '偏低' },
        { item: '血小板计数', result: '280', reference: '125-350', unit: '×10^9/L', status: '正常' },
        { item: '中性粒细胞比率', result: '68.5', reference: '40-75', unit: '%', status: '正常' },
        { item: '淋巴细胞比率', result: '25.2', reference: '20-50', unit: '%', status: '正常' },
        { item: '单核细胞比率', result: '4.8', reference: '3-10', unit: '%', status: '正常' },
        { item: '嗜酸性粒细胞比率', result: '1.2', reference: '1-4', unit: '%', status: '正常' },
        { item: '嗜碱性粒细胞比率', result: '0.3', reference: '0-1', unit: '%', status: '正常' }
      ],
      description: '血常规检查结果显示红细胞计数和血红蛋白轻度偏低，其他指标正常。',
      diagnosis: '轻度缺铁性贫血',
      suggestion: '建议：1. 补充铁剂治疗；2. 增加富含铁质的食物摄入，如瘦肉、肝脏、菠菜等；3. 同时补充维生素C促进铁吸收；4. 4-6周后复查血常规。'
    },
    {
      id: '2',
      examDate: '2024-01-12',
      reportDate: '2024-01-13',
      examType: '胸片',
      examName: '胸部X线检查',
      department: '放射科',
      doctorName: '李医生',
      technician: '赵技师',
      reportDoctor: '陈医生',
      status: 'completed',
      isRead: true,
      results: [],
      description: '胸部X线检查：双肺纹理清晰，未见明显实质性病变。心影大小正常，纵隔无移位。膈肌光滑，双侧肋膈角锐利。',
      diagnosis: '胸部X线检查正常',
      suggestion: '建议：胸部X线检查未见异常，请保持良好的生活习惯，定期体检。如有胸痛、咳嗽等症状请及时就诊。'
    },
    {
      id: '3',
      examDate: '2024-01-10',
      reportDate: '2024-01-11',
      examType: '生化检查',
      examName: '肝功能检查',
      department: '检验科',
      doctorName: '王医生',
      technician: '刘技师',
      reportDoctor: '黄医生',
      status: 'completed',
      isRead: true,
      results: [
        { item: '丙氨酸氨基转移酶(ALT)', result: '45', reference: '9-50', unit: 'U/L', status: '正常' },
        { item: '天门冬氨酸氨基转移酶(AST)', result: '38', reference: '15-40', unit: 'U/L', status: '正常' },
        { item: '总胆红素(TBIL)', result: '18.5', reference: '5.1-22.2', unit: 'μmol/L', status: '正常' },
        { item: '直接胆红素(DBIL)', result: '4.2', reference: '0-6.8', unit: 'μmol/L', status: '正常' },
        { item: '总蛋白(TP)', result: '72', reference: '65-85', unit: 'g/L', status: '正常' },
        { item: '白蛋白(ALB)', result: '42', reference: '40-55', unit: 'g/L', status: '正常' },
        { item: '球蛋白(GLO)', result: '30', reference: '20-40', unit: 'g/L', status: '正常' },
        { item: '白球比值(A/G)', result: '1.4', reference: '1.2-2.4', unit: '', status: '正常' }
      ],
      description: '肝功能检查结果显示各项指标均在正常范围内。',
      diagnosis: '肝功能正常',
      suggestion: '建议：肝功能检查正常，请继续保持健康的生活方式，避免过量饮酒，定期复查。'
    },
    {
      id: '4',
      examDate: '2024-01-08',
      reportDate: '2024-01-09',
      examType: '心电图',
      examName: '常规心电图检查',
      department: '心电图室',
      doctorName: '陈医生',
      technician: '张技师',
      reportDoctor: '李医生',
      status: 'completed',
      isRead: false,
      results: [
        { item: '心率', result: '72', reference: '60-100', unit: '次/分', status: '正常' },
        { item: 'PR间期', result: '0.16', reference: '0.12-0.20', unit: '秒', status: '正常' },
        { item: 'QRS间期', result: '0.08', reference: '0.06-0.10', unit: '秒', status: '正常' },
        { item: 'QT间期', result: '0.38', reference: '0.33-0.43', unit: '秒', status: '正常' }
      ],
      description: '心电图检查：窦性心律，心率72次/分，各波形正常，传导系统正常。',
      diagnosis: '窦性心律，心电图正常',
      suggestion: '建议：心电图检查正常，请保持规律作息，适量运动，避免过度疲劳。如有心悸、胸闷等症状请及时就诊。'
    },
    {
      id: '5',
      examDate: '2024-01-05',
      reportDate: '2024-01-06',
      examType: 'B超检查',
      examName: '腹部彩色多普勒超声',
      department: '超声科',
      doctorName: '赵医生',
      technician: '孙技师',
      reportDoctor: '周医生',
      status: 'completed',
      isRead: true,
      results: [],
      description: '腹部彩超检查：肝脏大小形态正常，实质回声均匀，肝内血管走行正常。胆囊大小形态正常，壁厚约2mm，囊内未见异常回声。胰腺显示清晰，实质回声均匀。脾脏大小正常。双肾大小形态正常，实质回声均匀，集合系统无扩张。',
      diagnosis: '腹部彩超检查未见异常',
      suggestion: '建议：腹部超声检查未见明显异常，请保持健康的饮食习惯，定期体检。如有腹痛、消化不良等症状请及时就诊。'
    },
    {
      id: '6',
      examDate: '2024-01-03',
      reportDate: '2024-01-04',
      examType: '尿常规',
      examName: '尿液常规检查',
      department: '检验科',
      doctorName: '吴医生',
      technician: '徐技师',
      reportDoctor: '郑医生',
      status: 'completed',
      isRead: true,
      results: [
        { item: '尿比重', result: '1.020', reference: '1.003-1.030', unit: '', status: '正常' },
        { item: 'pH值', result: '6.5', reference: '4.6-8.0', unit: '', status: '正常' },
        { item: '蛋白质', result: '阴性(-)', reference: '阴性', unit: '', status: '正常' },
        { item: '葡萄糖', result: '阴性(-)', reference: '阴性', unit: '', status: '正常' },
        { item: '酮体', result: '阴性(-)', reference: '阴性', unit: '', status: '正常' },
        { item: '隐血', result: '阴性(-)', reference: '阴性', unit: '', status: '正常' },
        { item: '白细胞', result: '0-2', reference: '0-5', unit: '/HP', status: '正常' },
        { item: '红细胞', result: '0-1', reference: '0-3', unit: '/HP', status: '正常' },
        { item: '管型', result: '未见', reference: '偶见透明管型', unit: '', status: '正常' }
      ],
      description: '尿常规检查结果显示各项指标均正常。',
      diagnosis: '尿常规检查正常',
      suggestion: '建议：尿常规检查正常，请保持充足的水分摄入，注意个人卫生，定期体检。'
    },
    {
      id: '7',
      examDate: '2024-01-01',
      reportDate: '2024-01-02',
      examType: 'CT检查',
      examName: '头颅CT平扫',
      department: '放射科',
      doctorName: '马医生',
      technician: '冯技师',
      reportDoctor: '何医生',
      status: 'completed',
      isRead: false,
      results: [],
      description: '头颅CT平扫：双侧大脑半球实质密度均匀，灰白质分界清楚。脑室系统大小形态正常，中线结构无移位。基底节区、丘脑区无异常密度影。小脑半球密度正常。颅骨完整，未见骨折征象。',
      diagnosis: '头颅CT检查未见异常',
      suggestion: '建议：头颅CT检查未见明显异常，如有头痛、头晕等症状持续，请及时复诊。平时注意休息，避免过度疲劳。'
    },
    {
      id: '8',
      examDate: '2023-12-28',
      reportDate: '2023-12-29',
      examType: '生化检查',
      examName: '血脂检查',
      department: '检验科',
      doctorName: '宋医生',
      technician: '韩技师',
      reportDoctor: '田医生',
      status: 'completed',
      isRead: true,
      results: [
        { item: '总胆固醇(TC)', result: '5.8', reference: '2.8-5.17', unit: 'mmol/L', status: '偏高' },
        { item: '甘油三酯(TG)', result: '2.1', reference: '0.45-1.69', unit: 'mmol/L', status: '偏高' },
        { item: '高密度脂蛋白胆固醇(HDL-C)', result: '1.1', reference: '>1.04', unit: 'mmol/L', status: '正常' },
        { item: '低密度脂蛋白胆固醇(LDL-C)', result: '3.8', reference: '<3.37', unit: 'mmol/L', status: '偏高' },
        { item: '载脂蛋白A1(ApoA1)', result: '1.25', reference: '1.20-1.60', unit: 'g/L', status: '正常' },
        { item: '载脂蛋白B(ApoB)', result: '1.15', reference: '0.80-1.05', unit: 'g/L', status: '偏高' }
      ],
      description: '血脂检查结果显示总胆固醇、甘油三酯、低密度脂蛋白胆固醇和载脂蛋白B偏高。',
      diagnosis: '高脂血症',
      suggestion: '建议：1. 调整饮食结构，减少高脂肪、高胆固醇食物摄入；2. 增加有氧运动，每周至少150分钟中等强度运动；3. 控制体重；4. 必要时考虑药物治疗；5. 3个月后复查血脂。'
    },
    {
      id: '9',
      examDate: '2023-12-25',
      reportDate: '2023-12-26',
      examType: 'MRI检查',
      examName: '腰椎MRI检查',
      department: '放射科',
      doctorName: '胡医生',
      technician: '邓技师',
      reportDoctor: '石医生',
      status: 'completed',
      isRead: true,
      results: [],
      description: 'T2WI矢状位及轴位扫描：腰椎生理弯曲存在。L4-5椎间盘轻度突出，向后突入椎管，对硬膜囊轻度压迫。L5-S1椎间盘信号减低，椎间隙轻度变窄。其余椎体及椎间盘未见明显异常。脊髓圆锥及马尾神经显示清楚。',
      diagnosis: 'L4-5椎间盘轻度突出，L5-S1椎间盘变性',
      suggestion: '建议：1. 避免久坐久站，注意腰部保暖；2. 进行适当的腰背肌锻炼；3. 避免重体力劳动；4. 症状明显时可考虑理疗、牵引等治疗；5. 定期复查。'
    },
    {
      id: '10',
      examDate: '2023-12-20',
      reportDate: '2023-12-21',
      examType: '生化检查',
      examName: '肾功能检查',
      department: '检验科',
      doctorName: '朱医生',
      technician: '潘技师',
      reportDoctor: '谢医生',
      status: 'completed',
      isRead: false,
      results: [
        { item: '血肌酐(Cr)', result: '85', reference: '57-111', unit: 'μmol/L', status: '正常' },
        { item: '血尿素氮(BUN)', result: '5.2', reference: '3.1-8.0', unit: 'mmol/L', status: '正常' },
        { item: '尿酸(UA)', result: '420', reference: '208-428', unit: 'μmol/L', status: '正常' },
        { item: '胱抑素C(CysC)', result: '0.95', reference: '0.51-1.09', unit: 'mg/L', status: '正常' },
        { item: '肾小球滤过率(eGFR)', result: '95', reference: '>90', unit: 'ml/min/1.73m²', status: '正常' }
      ],
      description: '肾功能检查结果显示各项指标均在正常范围内。',
      diagnosis: '肾功能正常',
      suggestion: '建议：肾功能检查正常，请保持充足的水分摄入，避免憋尿，少食高嘌呤食物，定期复查。'
    }
  ]
  
  reportsList.value = mockReports
  pagination.total = mockReports.length
  console.log('已加载丰富的模拟检查报告数据:', mockReports.length, '条')
}

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1
  loadReports()
}

// 重置搜索
const handleReset = () => {
  searchForm.examType = ''
  searchForm.status = ''
  dateRange.value = []
  pagination.currentPage = 1
  loadReports()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  loadReports()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadReports()
}

// 行点击处理
const handleRowClick = (row) => {
  if (row.status === 'completed') {
    handleViewReport(row)
  }
}

// 查看报告
const handleViewReport = (row) => {
  if (row.status !== 'completed') {
    ElMessage.warning('报告尚未完成，请稍后查看')
    return
  }
  
  currentReport.value = row
  reportDialogVisible.value = true
  
  // 标记为已读
  if (!row.isRead) {
    row.isRead = true
    // 这里应该调用API更新阅读状态
    updateReadStatus(row.id)
  }
}

// 更新阅读状态
const updateReadStatus = async (reportId) => {
  try {
    await patientAPI.markAsRead(reportId)
  } catch (error) {
    console.error('更新阅读状态失败:', error)
  }
}

// 下载报告
const handleDownloadReport = (row) => {
  if (row.status !== 'completed') {
    ElMessage.warning('报告尚未完成，无法下载')
    return
  }
  
  ElMessage.success('报告下载中...')
  // 这里应该调用下载API
  downloadReport(row.id)
}

// 下载当前报告
const handleDownloadCurrent = () => {
  if (currentReport.value) {
    handleDownloadReport(currentReport.value)
  }
}

// 下载报告文件
const downloadReport = async (reportId) => {
  try {
    // 模拟下载
    const link = document.createElement('a')
    link.href = `data:text/plain;charset=utf-8,检查报告ID: ${reportId}`
    link.download = `检查报告_${reportId}.pdf`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  }
}

// 查看检查历史
const handleViewHistory = (row) => {
  router.push(`/portal/patient/exam-history?type=${row.examType}`)
}

// 打印报告
const handlePrintReport = () => {
  window.print()
}

// 检查用户是否已登录并初始化数据
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再查看检查报告')
    router.push({
      path: '/portal/login',
      query: { redirect: '/portal/patient/reports' }
    })
    return
  }
  
  // 已登录，先获取患者信息，再加载检查报告数据
  try {
    await getCurrentPatient()
    await loadReports()
  } catch (error) {
    console.error('初始化数据失败:', error)
    // 即使获取患者信息失败，也尝试加载模拟数据
    loadMockData()
  }
})
</script>

<style scoped>
.reports-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-card, .reports-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-header, .reports-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-title, .reports-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.reports-stats {
  color: #666;
  font-size: 14px;
}

.stat-item {
  margin-left: 15px;
}

.search-form {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.report-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.report-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #e9ecef;
}

.report-header h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 20px;
}

.report-meta {
  color: #666;
  font-size: 14px;
}

.divider {
  margin: 0 10px;
}

.report-info {
  margin-bottom: 20px;
}

.detail-section {
  margin-top: 20px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.content-box {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  padding: 12px;
  min-height: 40px;
  line-height: 1.5;
}

.images-box {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.action-buttons .el-button {
  margin: 0;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .search-form :deep(.el-form-item) {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .reports-stats {
    margin-top: 10px;
  }
  
  .stat-item {
    display: block;
    margin-left: 0;
    margin-bottom: 5px;
  }
}
</style> 